package net.ghy.rules;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;  
import java.io.InputStreamReader;  
      
import java.io.UnsupportedEncodingException;

import javax.script.Invocable;  
import javax.script.ScriptEngine;  
import javax.script.ScriptEngineManager;  
import javax.script.ScriptException;       
public class RuleInvoker {
    
  /** 
   * 脚本引擎 
   */  
  private ScriptEngine engine = null;  
  /** 
   * 
   */  
  private ScriptEngineManager engineManager = null;  
        
  private Invocable invocable = null;  
        
  private InputStreamReader reader = null;  
        
  private InputStream inputStream = null;  
        
  private RuleProcessImpl ruleProcessImpl = null;  
        
  private RuleImpl ruleImpl = null;  
  
  //public static final String jsPath = LMService.pathRoot + File.separator
//			+ "lm.js";

        
  /** 
   * 执行规则 
   * @param obj 
   * @return 
 * @throws UnsupportedEncodingException 
   */  
  public Object execRule(Object obj) throws UnsupportedEncodingException{  
            
      return execRule(obj , "BXRule.js");  
  }  
  
  /** 
   * 
   * @param obj 
   * @param rule 
   * @return 
 * @throws UnsupportedEncodingException 
   */  
  public Object execRule(Object obj , String rule) throws UnsupportedEncodingException{  
      //创建规则脚本引擎  
      engineManager = new ScriptEngineManager();  
      engine = engineManager.getEngineByName("js");  
      //读取规则脚本  
      ClassLoader classLoader = RuleInvoker.class.getClassLoader();
      
      //System.out.println(this.getClass().getResourceAsStream(rule));
     // classLoader.g
      inputStream = classLoader.getResourceAsStream(rule);  
      reader = new InputStreamReader(inputStream,"utf-8");  
      try {  
          //执行规则脚本  
          engine.eval(reader);  
      } catch (ScriptException e) {  
          e.printStackTrace();  
      }  
      finally{  
          try {  
              if(null != reader){  
                  reader.close();  
              }  
              if(null != inputStream){  
                  inputStream.close();  
              }  
          } catch (Exception e) {  
              e.printStackTrace();  
          }  
      }  
      invocable = (Invocable)engine;  
      if(rule.endsWith(".rp")){  
          ruleProcessImpl =  invocable.getInterface(RuleProcessImpl.class);  
          rule = ruleProcessImpl.start(obj);  
          return execRule(obj , rule);  
      }  
      else{  
          ruleImpl =  invocable.getInterface(RuleImpl.class);  
          return ruleImpl.start(obj);  
      }  
  } 
  public static void main(String[] args) throws Exception {   
	  RuleInvoker ri = new RuleInvoker();
	  Test a = new Test();
	  ri.execRule(a);
	  System.out.println(a.result);
} 
}
